package cn.unknownerror.ueteam;

import cn.unknownerror.ueteam.commands.TeamCommand;
import cn.unknownerror.ueteam.data.*;
import cn.unknownerror.ueteam.listener.*;
import cn.unknownerror.ueteam.team.NormalTeam;
import cn.unknownerror.ueteam.team.TeamAPI;
import cn.unknownerror.ueteam.team.TeamException;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;

public class PluginUETeam extends JavaPlugin {

    private static PluginUETeam instance;
    private ConfigurationManager config;
    private StorageUnit storageUnit;
    @Override
    public void onEnable(){
        preload();
        //registerListenerIfTrue(new PrefixListener(config),"Team.Chatting.enable");
        //registerListenerIfTrue(new ExpSharingListener(),"Team.Exp_Sharing.enable");
        Bukkit.getPluginManager().registerEvents(new PlayerChatListener(),this);
        Bukkit.getPluginManager().registerEvents(new PrefixListener(config),this);
        Bukkit.getPluginManager().registerEvents(new TeamListener(),this);
        Bukkit.getPluginManager().registerEvents(new PlayerActionListener(),this);

        Bukkit.getPluginCommand("Team").setExecutor(new TeamCommand(config));
    }
    public static PluginUETeam getInstance(){
        return instance;
    }

    public void preload(){
        this.config=new ConfigurationManager(this,"config.yml");
        this.config.load();

        File directory = new File("");
        storageUnit = new SQLiteUnit(directory.getAbsolutePath()+"\\plugins\\UETeam\\data.db");
        //Team初始化
        TeamAPI.readData(storageUnit.getPTT());
        for(Data data:storageUnit.getTeamData()){//读取Team列表
            try {
                new NormalTeam(data);
            } catch (TeamException e) {
                Bukkit.getServer().getLogger().warning(e.toString());
                for(StackTraceElement element : e.getStackTrace()){
                    Bukkit.getServer().getLogger().warning(element.toString());
                }
            }
        }
        NormalTeam.setExp_share(config.getConfig().getDouble("Team.Exp_Sharing.proportion"));
        NormalTeam.setRadius(config.getConfig().getInt("Team.Exp_Sharing.radius",0));
        if(config.getConfig().getBoolean("Team.Exp_Sharing.enable",true)) NormalTeam.setExp_share(1);
        //Team初始化结束
        instance=this;
    }
    @Override
    public void onDisable(){
        storageUnit.savePTT(TeamAPI.getData());
        for(NormalTeam team:NormalTeam.getTeams()){
            storageUnit.saveTeamData(team.getMeta().toData());
        }
        getLogger().info("插件已关闭");
    }

    public ConfigurationManager getConfigurationManager(){
        return config;
    }

    private void registerListenerIfTrue(Listener listener, String path){
        if(config.getConfig().getBoolean(path)){
            Bukkit.getServer().getPluginManager().registerEvents(listener,this);
        }
    }
}
